package com.comprehensive.personalnovel.service.impl;

import com.comprehensive.common.dto.PageResponse;
import com.comprehensive.common.po.Novel;
import com.comprehensive.common.po.NovelChapter;
import com.comprehensive.personalnovel.feign.FileServiceFeignClient;
import com.comprehensive.personalnovel.feign.NovelFeignClient;
import com.comprehensive.personalnovel.service.NovelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class NovelServiceImpl implements NovelService {
    // 匹配章节的正则表达式，可根据实际小说格式调整
    // 匹配"第一章"、"第1章"、"第一章 标题"、"第1章 标题"等格式
    private static final String CHAPTER_PATTERN = "第[零一二三四五六七八九十百千万0-9]+章(\\s+.*)?";
    @Autowired
    private FileServiceFeignClient fileServiceFeignClient;
    @Autowired
    private NovelFeignClient novelFeignClient;

    // 测试方法
    public static void main(String[] args) {
        // 替换为你的小说文件路径
        String novelPath = "D:\\upload\\半仙.txt";
        NovelServiceImpl novelService = new NovelServiceImpl();
        novelService.readNovelChapter(novelPath,"1");
    }

    @Override
    public PageResponse<Novel> listPage(int pageNum, int pageSize) {
        return novelFeignClient.listPage(pageNum, pageSize);
    }

    @Override
    public Novel queryById(String id) {
        return novelFeignClient.queryById(id);
    }

    @Override
    public void save(Novel novel) {
        novelFeignClient.save(novel);
    }

    @Override
    public void update(Novel novel) {
        novelFeignClient.update(novel);
    }

    @Override
    public void delete(String id) {
        List<NovelChapter> novelChapters = novelFeignClient.listChapter(id);
        if (!novelChapters.isEmpty()){
            for (NovelChapter novelChapter : novelChapters) {
                novelFeignClient.deleteChapter(String.valueOf(novelChapter.getId()));
            }
        }
        novelFeignClient.delete(id);
    }

    @Override
    public PageResponse<NovelChapter> listChapterPage(int pageNum, int pageSize, String novelId) {
        return  novelFeignClient.listChapterPage(pageNum, pageSize, novelId);
    }

    @Override
    public NovelChapter queryChapterById(String id) {
        return novelFeignClient.queryChapterById(id);
    }

    @Override
    public void saveChapter(NovelChapter novelChapter) {
        novelFeignClient.saveChapter(novelChapter);
    }

    @Override
    public void updateChapter(NovelChapter novelChapter) {
        novelFeignClient.updateChapter(novelChapter);
    }

    @Override
    public void deleteChapter(String id) {
        novelFeignClient.deleteChapter(id);
    }

    /**
     * 读取小说文件并提取章节
     * @param filePath 小说文件路径
     * @return 章节列表
     */
    @Override
    public void readNovelChapter(String filePath,String novelId) {
        Novel novel = novelFeignClient.queryById(novelId);
        if (novel==null){
            throw new RuntimeException("小说不存在");
        }
        try {
            // 读取文件所有行
            List<String> lines = Files.readAllLines(Paths.get(filePath), Charset.forName("GBK"));

            // 拼接所有行成一个字符串，处理换行
            StringBuilder fullText = new StringBuilder();
            for (String line : lines) {
                // 去除每行前后空格，空行用换行符保留
                String processedLine = line.trim();
                fullText.append(processedLine).append("\n");
            }

            // 编译正则表达式
            Pattern pattern = Pattern.compile(CHAPTER_PATTERN);
            Matcher matcher = pattern.matcher(fullText);

            List<Integer> chapterPositions = new ArrayList<>();
            List<String> chapterTitles = new ArrayList<>();

            // 查找所有章节位置和标题
            while (matcher.find()) {
                chapterPositions.add(matcher.start());
                chapterTitles.add(matcher.group());
            }

            // 提取每个章节的内容
            for (int i = 0; i < chapterTitles.size(); i++) {
                NovelChapter novelChapter = new NovelChapter();
                int start = chapterPositions.get(i);
                int end = (i < chapterPositions.size() - 1) ?
                        chapterPositions.get(i + 1) : fullText.length();

                // 提取章节内容（从章节标题开始到下一章节标题前）
                String content = fullText.substring(start, end)
                        .replace(chapterTitles.get(i), "")
                        .trim();
                novelChapter.setNovelId(novelId);
                novelChapter.setTitle(chapterTitles.get(i));
                novelChapter.setSort(i);
                novelChapter.setContent(content);
                novelFeignClient.saveChapter(novelChapter);
                //log.info("章节标题：{}，章节内容：{}", chapterTitles.get(i), content);
            }

        } catch (IOException e) {
            throw new RuntimeException("读取文件出错：" + e.getMessage());
        }
    }
}